package jmind.core.aspect;

import jmind.core.annotation.CacheMonitor;
import jmind.core.cache.xmemcached.Memcached;
import jmind.core.manager.MemcachedManager;
import jmind.core.support.MethodSupport;
import jmind.core.util.DataUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @CacheMonitor( key = "'user",exp=3600)
 *  @CacheMonitor(prefix ="user", exp = GlobalConstants.HOUR, spel = "mac")
 * key 用做前缀+ 方法参数值
 * @author wbxie
 * @Component
@Aspect  好像什么时候都需要打这个标签
 * 2013-12-4
 */
@Aspect
public class CacheAspect {

    @Pointcut("@annotation(jmind.core.annotation.CacheMonitor)")
    public void exe2() {
    }

    @Around("exe2()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        return doit(pjp);
    }

    private Object doit(ProceedingJoinPoint pjp) throws Throwable {

        final CacheMonitor m = JoinPoints.getAnnotation(pjp, CacheMonitor.class);
        // MethodSignature signature = (MethodSignature) pjp.getSignature();
        // System.out.println(signature.getDeclaringTypeName() + "&" + signature.getName() + "&"
        //         + signature.toLongString() + "&" + signature.toShortString() + "&" + signature.getDeclaringType());
        //  System.out.println(signature.getMethod().getName()+"%"+signature.getReturnType());
        //      com.zhimei.platform.web.controller.TestController&test2&public java.lang.String com.zhimei.platform.web.controller.TestController.test2(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)&TestController.test2(..)&class com.zhimei.platform.web.controller.TestController
        //      test2%class java.lang.String
        //      DBObject arr = new BasicDBObject("cla", signature.getDeclaringTypeName());
        //      arr.put("method", signature.getName());
        //      arr.put("arg", pjp.getArgs()[0]);
        //      arr.put("exp", m.type().name());
        //      arr.put("key", key);
        //      System.out.println(arr);

        // key 用做前缀 ,当spel不为空时，取第一个对象的属性值
        String key = m.spel().isEmpty() ? DataUtil.composeKey(m.prefix(), pjp.getArgs()) : m.prefix()
                + MethodSupport.getProperty(pjp.getArgs()[0], m.spel());

        Memcached cache = MemcachedManager.getInstance().getResource(m.name());
        //添加参数值 做为key
        if (m.remove()) {
            cache.delete(key);
            return pjp.proceed();
        }
        Object obj = cache.get(key);
        if (obj == null) {
            obj = pjp.proceed();
            if (obj != null)
                cache.set(key, m.exp(), obj);
        }
        return obj;

    }

}
